package jamun

object Downloader {
  def get(urlStr:String, toFileName:String) = {
    println("Downloading: " + urlStr + "\nTo: " + toFileName)
    try {
      val connection = (new java.net.URL(urlStr)).openConnection
      val length = connection.getContentLength

      val inputStream = connection.getInputStream
      val buffSize = 1024
      val fileWriter = (new java.io.FileOutputStream(toFileName))
      val byteBuff = new Array[Byte](buffSize)
      var bytesRead = 0
      var totalBytesRead = 0
      var done = false
      do {
        bytesRead = inputStream read (byteBuff)
        if (bytesRead < 0) done = true
        else {
          assert(bytesRead != 0)
          fileWriter write (byteBuff, 0, bytesRead)
          totalBytesRead += bytesRead
          printPercent(totalBytesRead, length)
        }
      } while (!done)
      println("")

      inputStream.close
      fileWriter.close

      true
    } catch {
      case e:java.io.IOException => println(e); false
    }
  }

  def printPercent(actual:Int, total:Int) = {
    print("\r" + ((actual * 100) / total) + "% of [ " + total + " b]"); Console.out.flush
  }
}
